jQuery.fn.center = function() {
	this.css("position", "absolute");
	this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
	this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
	return this;
}

String.format = function( text ) {
    //check if there are two arguments in the arguments list

    if ( arguments.length <= 1 ) {
        //if there are not 2 or more arguments there's nothing to replace
        //just return the original text
        return text;
    }
    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for( var token = 0; token <= tokenCount; token++ ){
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace( new RegExp( "\\{" + token + "\\}", "gi" ), arguments[ token + 1 ] );
    }
    return text;
};

$.extend({
	doPostGetLocationList:function(pid, obj, url) {		
		$.post(url, 
			{parentID: pid}, 
			function(xml) {
				var str = $.getXMLStringOf(xml, 'location');
				$(obj).html(str);
			}
		);
	},
	doPostGetCategoryList:function(pid, obj, url) {		
		$.post(url, 
			{parentID: pid}, 
			function(xml) {
				var str = $.getXMLStringOf(xml, 'category');		
				$(obj).html(str);
			}
		);
	},
	getXMLObject:function(xml) {
		try { //Internet Explorer
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async = "false";
			xmlDoc.loadXML(xml);
		} catch(e){ //Firefox et. all
			try {
				parser = new DOMParser();
				xmlDoc = parser.parseFromString(xml, "text/xml");
				xmlDoc.async = "false";
			} catch (e) {
				alert(e.message);
				return null;
			}
		} finally {
			return xmlDoc;
		}
	},
	getSingleNode:function(name, xmlDoc) {
		xmlDoc = $.getXMLObject(xmlDoc);
		var obj = xmlDoc.getElementsByTagName(name)[0];
		return obj.text;
	},
	getStringFromXMLQuestions:function(xml) {
		xmlDoc = $.getXMLObject(xml);
		if (xmlDoc != null) {			
			var questionList = xmlDoc.getElementsByTagName('Question');
			var str = '';
			if (questionList.length > 0) {				
				for ( var i = 0; i < questionList.length; i++) {
					var question = questionList[i];
					str += '<b>' + question.getAttribute('content') + '</b><br />';
					var answerList = question.getElementsByTagName('answer');
					for (var j = 0; j < answerList.length; j++) {
						var answer = answerList[j];
						str += '<input type="radio" value="' + question.getAttribute('id') + '-' 
							+ answer.getAttribute('id') 
							+ '" name="' + question.getAttribute('id') + '" />'
							+ answer.getAttribute('content') + '<br />'; 
					}					
				}
			}
			return str;
		}
	},
	getStringFromXMLProviders:function(xml) {
		var str = '';
		xmlDoc = $.getXMLObject(xml);
		if (xmlDoc != null) {			
			var providerList = xmlDoc.getElementsByTagName('Provider');
			if (providerList.length > 0) {				
				str += '<fieldset class="form"><ol>';
				provider = providerList[0];
				var url = "index.php?view&type=provider&id=" + provider.getAttribute('id');
				str += '<li class="input"><input type="radio" name="ckDiaDiem" checked="checked" value="' 
					+ provider.getAttribute('id') + '" />'
					+ '<a href="' + url + '">' + provider.getAttribute('name') + ' - ' 
					+ provider.getAttribute('address') + '</a>'
					+ '</li>';
				for ( var i = 1; i < providerList.length; i++) {
					provider = providerList[i];
					url = "index.php?view&type=provider&id=" + provider.getAttribute('id');
					str += '<li class="input"><input type="radio" name="ckDiaDiem" value="' 
						+ provider.getAttribute('id') + '" />'
						+ '<a href="' + url + '">' + provider.getAttribute('name') + ' - ' 
						+ provider.getAttribute('address') + '</a>'
						+ '</li>';
				}
				str += '</ol></fieldset>';
			}
			return str;
		}
	},
	//get ket qua danh gia item tu dialog box
	getDanhGiaItem:function() {
		str = '';
		$('#contentDanhGiaItem input[type=radio]:checked').each(				
			function(index){				
				str += $(this).val() + ' ';				
			}
		);
		return str;
	},
	//get ket qua danh gia item tu dialog box
	getDanhGiaProvider:function() {
		str = '';
		$('#contentDanhGiaProvider input[type=radio]:checked').each(				
			function(index){				
				str += $(this).val() + ' ';				
			}
		);
		return str;
	},
	//chuyen danh sach cac povider
	getXMLStringOf:function(xml, name, selVal) {
		xmlDoc = $.getXMLObject(xml);
		if (xmlDoc != null) {
			var locationList = xmlDoc.getElementsByTagName(name);
			var str = '';
			
			for ( i = 0; i < locationList.length; i++) {
				var location = locationList[i];
				var id = location.getAttribute("id");
				var name = location.getAttribute("name");
				
				if ((i === 0 && selVal === undefined) || (name === selVal)) {
					str += '<option value="' + id + '" selected="selected">' + name + '</option>';
				} else {
					str += '<option value="' + id + '">' + name + '</option>';
				}
			}				
				
			return str;
		} else {
			return '';
		}
	},
	removeRow:function(tag) {		
		$(tag).parent().parent().remove();
	},
	emailValidate:function(strEmail) {
		validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;			

		if (strEmail.search(validRegExp) == -1) {
			return false;
		}
		return true;
	},
	isDate:function(dtStr) {
		var daysInMonth = DaysArray(12);
		var pos1 = dtStr.indexOf(dtCh);
		var pos2 = dtStr.indexOf(dtCh, pos1 + 1);
		var strDay = dtStr.substring(0, pos1);
		var strMonth = dtStr.substring(pos1 + 1, pos2);
		var strYear = dtStr.substring(pos2 + 1);
		
		strYr = strYear;
		if (strDay.charAt(0)=="0" && strDay.length>1) 
			strDay=strDay.substring(1);
		if (strMonth.charAt(0)=="0" && strMonth.length>1) 
			strMonth=strMonth.substring(1);
		for (var i = 1; i <= 3; i++) {
			if (strYr.charAt(0)=="0" && strYr.length>1) { 
				strYr=strYr.substring(1);
			}
		}
		month = parseInt(strMonth);
		day = parseInt(strDay)
		year = parseInt(strYr)
		if (pos1 == -1 || pos2 == -1) {
			return false;				
		}
		if (strMonth.length < 1 || month < 1 || month > 12) {
			return false;
		}
		if (strDay.length < 1 || day < 1 || day > 31 || ( month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]){
			return false;
		}
		if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear) {
			return false;
		}
		if (dtStr.indexOf(dtCh, pos2 + 1) != -1 || isInteger(stripCharsInBag(dtStr, dtCh))==false) {
			return false;
		}
		return true;	
	},
	trim : function(s) {
		return $.rtrim($.ltrim(s));		
	},
	ltrim : function(s) {
		var l=0;
		while(l < s.length && s[l] == ' ') {	
			l++; 
		}
		return s.substring(l, s.length);
	},
	rtrim :function(s) {
		var r = s.length - 1;
		
		while(r > 0 && s[r] == ' ') {	
			r-=1;	
		}
		
		return s.substring(0, r+1);
	},
	clearInAllOptionsInCombo:function(ele, addBlank) {
		$(ele).find('option').remove().end();
		if (addBlank == true) {
			$(ele).append($('<option></option>'));
		}
	},
	loadListLocation : function(ele, parent, addEmpty, defaultValue) {
		$.post('index.php?location&action=loadAllByParentByJSON', {parentID:parent}, function(data) {
			$.clearInAllOptionsInCombo($(ele), addEmpty);
			var list = $.parseJSON(data);
			for (var i = 0; i < list.length; i++) {
				$(ele).append($('<option></option>').val(list[i].id).html(list[i].name));
			}
			if (defaultValue) {
				$(ele).val(defaultValue);
				$(ele).trigger('change');
			}
		});
	},
	postToGetListLocation : function(ele, updatedEle, addEmpty, defaultValue) {
		var location = $(ele).val();
		if (location != null && location != '') {
			$.loadListLocation($(updatedEle), location, addEmpty, defaultValue);		
		}
	}
});		

$(document).ready(function(){
	var loadingIcon = $('<div></div>').addClass('loadingBox');
	loadingIcon.append($('<div></div>').addClass('loadingDiv').css('position', 'relative').css('margin', 'auto'));
	loadingIcon.append($('<div></div>').html('Đang load...').css('position', 'relative'));
	$('body').append($(loadingIcon).center());
	$(loadingIcon).hide();
	$(loadingIcon).ajaxStart(function() {
        $(loadingIcon).show();
    });
    $(loadingIcon).ajaxStop(function() {
        $(loadingIcon).hide();
    });
});
